package student.aistar.day12;

import java.math.BigDecimal;

/**
 * 面试题 - java中如何处理小数计算的精度丢失问题
 */
public class BigDecimalDemo {
    public static void main(String[] args) {
        //小数在进行计算的时候会有精度的丢失
        System.out.println(0.1 + 0.2);//0.30000000000000004
        System.out.println(0.1 - 0.2);//-0.1
        //再除不尽的时候, 还是会发生精度丢失
        System.out.println(0.3 / 0.2);//1.4999999999999998
        //在整除时, 如果除不尽的时候, 也会发生精度丢失
        System.out.println(0.2 % 0.3);//0.2
        //相乘的时候也会发生精度丢失
        System.out.println(0.1 * 0.2);//0.020000000000000004

        BigDecimal d1 = new BigDecimal(0.1);
        BigDecimal d2 = new BigDecimal(0.2);

        System.out.println(d1.add(d2));//0.3000000000000000166533453693773481063544750213623046875

        System.out.println(d1.divide(d2));//0.5
        System.out.println(d1.multiply(d2));//0.0200000000000000022204460492503131424770215565731879227912941627176741932192527428924222476780414581298828125

        System.out.println(d1.subtract(d2));//-0.1000000000000000055511151231257827021181583404541015625
    }
}
